<template>
  <div class="phyorgan">
    <ZljHeader :msg="msg"></ZljHeader>
    <el-container style="background-color: #f5f7fa; padding: 0">
      <el-main
        style="margin: 1rem 1rem 0 1rem; background-color: rgb(255, 255, 255)"
      >
        <div class="phy_main">
          <div class="title_2">数据筛选</div>
          <el-form class="search_line" :model="form" label-width="120px">
            <el-form-item label="输入查询:">
              <el-input
                size="small"
                style="width: 100px"
                v-model="form.name"
                placeholder="机构ID或名称"
              />
            </el-form-item>
            <!-- 省、市下拉框 -->
            <el-form-item class="provin-city" label="所在城市:">
              <el-select
                size="small"
                style="width: 80px"
                v-model="form.provin_sel"
                @change="search_cities(form.provin_sel)"
                placeholder="选择省"
              >
                <el-option
                  v-for="(province, index) in province_options"
                  :key="province.provinceId"
                  :label="province.provinceName"
                  :value="province.provinceId"
                />
              </el-select>
              <el-select
                size="small"
                style="width: 80px"
                v-model="form.city_sel"
                placeholder="选择市"
              >
                <el-option
                  v-for="(city, index) in city_options"
                  :key="city.cityId"
                  :label="city.cityName"
                  :value="city.cityId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="机构类型:">
              <el-select
                size="small"
                style="width: 120px"
                v-model="form.instype"
                placeholder="机构类型"
              >
                <el-option
                  v-for="(institu, index) in institu_options"
                  :key="institu.id"
                  :label="institu.type"
                  :value="institu.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否启用:">
              <el-select
                size="small"
                style="width: 90px"
                v-model="form.is_using"
                placeholder="是否启用"
              >
                <el-option label="全部" :value="using_options[0]" />
                <el-option label="是" :value="using_options[1]" />
                <el-option label="否" :value="using_options[2]" />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-left:-100px;">
              <el-button
                @click="search"
                size="small"
                type="primary"
                style="color: rgb(255, 255, 255)"
                >查询</el-button
              >
              <el-button plain size="small" @click="reset">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="three-buttons">
            <el-button plain @click="addFormVisible = true">添加</el-button>
            <el-popconfirm
              confirm-button-text="已√的"
              cancel-button-text="未√的"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="删除哪些部分呢?"
              @confirm="del_checked"
              @cancel="del_unchecked"
            >
              <template #reference>
                <el-button plain>删除</el-button>
              </template>
            </el-popconfirm>
            <el-button plain>导入</el-button>
            <el-button size="small" plain @click="downloadExcel"
              >下载Excel模板</el-button
            >
          </div>
          <!-- 表格 -->
          <el-table
            border
            :data="organization"
            @selection-change="handleSelectionChange"
            :header-cell-style="{ textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            stripe
          >
            <el-table-column type="selection" #default="scope"
              ><template
                v-if="scope.row.organId == null"
                style="textalign: 'center'"
              >
              </template
            ></el-table-column>
            <el-table-column property="organId" label="机构ID" />
            <el-table-column property="organName" label="机构名称" />
            <el-table-column property="subName" label="分支机构" />
            <el-table-column property="cityName" label="所在城市" />
            <el-table-column property="typeName" label="机构类型" />
            <el-table-column property="phone" label="电话" />
            <el-table-column property="isUsed" label="是否启用" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  style="color: rgb(95, 208, 168)"
                  v-if="scope.row.organId != null"
                  @click.prevent="update_org(scope.row, scope.$index)"
                >
                  修改
                </el-button>
                <el-button
                  link
                  type="primary"
                  size="small"
                  style="color: rgb(95, 208, 168)"
                  v-if="scope.row.organId != null"
                  @click.prevent="off_line(scope.row, scope.$index)"
                >
                  离线号源设置
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="demo-pagination-block">
            <el-config-provider :locale="zhCn">
              <el-pagination
                class="custom-pagination"
                v-if="organization.length > 0"
                v-model:current-page="page"
                v-model:page-size="size"
                :page-sizes="[5, 6, 8, 10]"
                :small="small"
                :disabled="disabled"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalcount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              >
              </el-pagination>
            </el-config-provider>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
  <!-- 新增体检机构的对话框 -->
  <el-dialog v-model="addFormVisible" title="新增体检机构">
    <Hhhupadd
      :provinceoptions="province_options"
      :show_img="noshowimg"
      :show_remove="false"
    ></Hhhupadd>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click="add_click"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 修改体检机构的对话框 -->
  <el-dialog v-model="updateFormVisible" title="修改体检机构信息">
    <Hhhupadd
      :provinceoptions="province_options"
      :show_img="isshowimg"
      :updateform="update_form"
      :show_remove="true"
    ></Hhhupadd>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="updateFormVisible = false">取消</el-button>
        <el-button type="primary" @click="update_organ"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 新增里面的大图显示 -->
  <!-- <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog> -->
  <!-- 离线号源设置 -->
  <el-dialog
    v-model="offVisible"
    title="离线号源设置(周期为一个月)"
    style="width: 56%"
  >
    <div class="formulate-line">
      <el-button @click="sourcerule" plain>配置号源规则</el-button>
      <div>
        <el-tag
          class="ml-2"
          type="success"
          size="large"
          style="
            font-size: 13px;
            background-color: #f0fff0;
            color: #afeeee;
            border: 0;
          "
          >所属机构 :
        </el-tag>
        <el-tag
          class="ml-2"
          size="large"
          effect="plain"
          style="
            font-size: 13px;
            background-color: rgb(208, 208, 254);
            color: #f0ffff;
            border: 0;
          "
          >{{ of_organ }}
        </el-tag>
        <el-tag
          class="ml-2"
          size="large"
          effect="plain"
          style="
            font-size: 13px;
            color: rgb(208, 208, 254);
            border: 1px solid rgb(208, 208, 254);
          "
          >{{ of_suborgan }}
        </el-tag>
      </div>
    </div>
    <el-calendar>
      <template #date-cell="{ data }">
        <div class="formulate-outer">
          <div class="off-linenumso" @click="is_updateshow(data)">
            <div>{{ data.day.split("-").slice(1).join("-") }}</div>
            <div>
              <div
                :class="[
                  new Date(
                    new Date().getFullYear(),
                    new Date().getMonth(),
                    new Date().getDate()
                  ).getTime() >
                  new Date(
                    new Date(data.day).getFullYear(),
                    new Date(data.day).getMonth(),
                    new Date(data.day).getDate()
                  ).getTime()
                    ? 'totnumso-2'
                    : 'totnumso-1',
                ]"
              >
                <div class="sign"></div>
                <span>{{ "总号源 :" }}</span>
                <div class="number">
                  <!-- 找到号源对应的日期 -->
                  {{
                    cander_data.find((item) => item.date === data.day)
                      ? cander_data.find((item) => item.date === data.day)
                          .totalNum
                      : ""
                  }}
                  <!-- 如果日历的日期大于号源日期的最后一天 -->
                  {{
                    new Date(
                      new Date(last_day).getFullYear(),
                      new Date(last_day).getMonth(),
                      new Date(last_day).getDate()
                    ).getTime() <
                    new Date(
                      new Date(data.day).getFullYear(),
                      new Date(data.day).getMonth(),
                      new Date(data.day).getDate()
                    ).getTime()
                      ? "待定"
                      : ""
                  }}
                  <!-- 如果日历的日期小于号源日期的最后一天 -->
                  {{
                    new Date(
                      new Date(first_day).getFullYear(),
                      new Date(first_day).getMonth(),
                      new Date(first_day).getDate()
                    ).getTime() >
                    new Date(
                      new Date(data.day).getFullYear(),
                      new Date(data.day).getMonth(),
                      new Date(data.day).getDate()
                    ).getTime()
                      ? "失效"
                      : ""
                  }}
                </div>
              </div>
              <div
                :class="[
                  new Date(
                    new Date().getFullYear(),
                    new Date().getMonth(),
                    new Date().getDate()
                  ).getTime() >
                  new Date(
                    new Date(data.day).getFullYear(),
                    new Date(data.day).getMonth(),
                    new Date(data.day).getDate()
                  ).getTime()
                    ? 'remainder-2'
                    : 'remainder-1',
                ]"
              >
                <div class="sign"></div>
                <span>{{ "余数 :" }}</span>
                <div class="number">
                  {{
                    cander_data.find((item) => item.date === data.day)
                      ? cander_data.find((item) => item.date === data.day).yuNum
                      : ""
                  }}<!-- 如果日历的日期大于号源日期的最后一天 -->
                  {{
                    new Date(
                      new Date(last_day).getFullYear(),
                      new Date(last_day).getMonth(),
                      new Date(last_day).getDate()
                    ).getTime() <
                    new Date(
                      new Date(data.day).getFullYear(),
                      new Date(data.day).getMonth(),
                      new Date(data.day).getDate()
                    ).getTime()
                      ? "待定"
                      : ""
                  }}
                  <!-- 如果日历的日期小于号源日期的最后一天 -->
                  {{
                    new Date(
                      new Date(first_day).getFullYear(),
                      new Date(first_day).getMonth(),
                      new Date(first_day).getDate()
                    ).getTime() >
                    new Date(
                      new Date(data.day).getFullYear(),
                      new Date(data.day).getMonth(),
                      new Date(data.day).getDate()
                    ).getTime()
                      ? "失效"
                      : ""
                  }}
                </div>
              </div>
            </div>
          </div>
          <div
            class="update-formulate"
            v-if="
              update_show == data.day ||
              new Date(
                new Date().getFullYear(),
                new Date().getMonth(),
                new Date().getDate()
              ).getTime() >
                new Date(
                  new Date(data.day).getFullYear(),
                  new Date(data.day).getMonth(),
                  new Date(data.day).getDate()
                ).getTime()
            "
            @click="update_show = ''"
          >
            <el-button
              @click="update_mulate(data.day)"
              size="small"
              v-if="
                update_show == data.day &&
                !(
                  new Date(
                    new Date(last_day).getFullYear(),
                    new Date(last_day).getMonth(),
                    new Date(last_day).getDate()
                  ).getTime() <
                  new Date(
                    new Date(data.day).getFullYear(),
                    new Date(data.day).getMonth(),
                    new Date(data.day).getDate()
                  ).getTime()
                ) &&
                !(
                  new Date(
                    new Date(first_day).getFullYear(),
                    new Date(first_day).getMonth(),
                    new Date(first_day).getDate()
                  ).getTime() >
                  new Date(
                    new Date(data.day).getFullYear(),
                    new Date(data.day).getMonth(),
                    new Date(data.day).getDate()
                  ).getTime()
                )
              "
              >修改号源</el-button
            >
            <!-- <el-button
              v-if="
                new Date(
                  new Date().getFullYear(),
                  new Date().getMonth(),
                  new Date().getDate()
                ).getTime() >
                new Date(
                  new Date(data.day).getFullYear(),
                  new Date(data.day).getMonth(),
                  new Date(data.day).getDate()
                ).getTime()
              "
              >不可修改</el-button
            > -->
          </div>
        </div>
      </template>
    </el-calendar>
  </el-dialog>
  <el-dialog
    v-model="formulateVisible"
    title="制定号源规则"
    @close-auto-focus="rulecancel"
  >
    <el-form :model="mulate_form" class="mulate-rule">
      <el-form-item>
        <span><i>*</i>生效时间 :</span>
        <el-date-picker
          v-model="mulate_form.time"
          :disabled-date="disabledDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <span><i>*</i>重复 :</span>
        <el-checkbox-group v-model="mulate_form.repetition">
          <el-checkbox
            v-for="weekday in weekdays"
            :label="weekday.val"
            name="type"
            >{{ weekday.val }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <span><i>*</i>可预约号源数 :</span>
        <el-input v-model="mulate_form.subscribe" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="rulecancel">取消</el-button>
        <el-button type="primary" @click="ruleconfirm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 修改单个号源弹窗 -->
  <el-dialog v-model="upmulateVisible" title="修改号源" style="width: 30%">
    <div class="update-source">
      <el-tag
        class="ml-2"
        size="large"
        style="
          font-size: 13px;
          background-color: #f0fff0;
          color: #9ff2f2;
          border: 0;
        "
        type="success"
        >{{ date_show }}
      </el-tag>
      <div>
        <span>总号源 :</span>
        <el-input v-model="update_source.totalNum"></el-input>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="upmulateVisible = false">取消</el-button>
        <el-button type="primary" @click="upmulate_con"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, h, computed, onMounted } from "vue";
import { ElTable, ElMessage, ElMessageBox, genFileId } from "element-plus";
import type {
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadUserFile,
} from "element-plus";
import { InfoFilled, Plus, UploadFilled } from "@element-plus/icons-vue";
import "element-plus/theme-chalk/index.css";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import { saveAs } from "file-saver";
import * as XLSX from "xlsx";
import {
  examorgan,
  province_all,
  city_search,
  search_all,
  addorgan,
  stock_list,
  type_all,
  updateorgan,
  delbatches,
  update_stock,
  update_Batches,
} from "../apis/phyorgan";
import Hhhupadd from "./../components/Hhhupadd.vue";
import ZljHeader from "./../components/ZljHeader.vue";
import { usephyorganStore } from "./../stores/phyorgan";
import { log } from "console";
const store = usephyorganStore();
let msg = "体检机构管理";

let form: any = reactive({
  name: "",
  provin_sel: "",
  city_sel: "",
  instype: "",
  is_using: "",
});
interface ProvinceOption {
  //省数组的类型
  provinceName: string;
  provinceId: number;
}

interface CityOption {
  //市数组的类型
  cityName: string;
  cityId: number;
}

let province_options: ProvinceOption[] = reactive([]); //省选择(子组件Hhhupadd也是用这个)
let city_options: CityOption[] = reactive([]); //市选择
let institu_options: any = reactive([]); //机构类型选择
let using_options = reactive([0, 1, 2]); //是否启用选择
let noshowimg = ref(false); //新增机构表单不显示图片
let isshowimg = ref(true); //修改机构表单显示图片
let all_organ = reactive([]); //所有的机构信息
let of_organ = ref("主机构");
let of_suborgan = ref("分支机构");
// 列表查询所有
let searchall = async () => {
  await search_all({}).then((res) => {
    // console.log(res.data.data);
    all_organ.length = 0;
    all_organ.push(...res.data.data);
  });
};
searchall();

let sub_id = ref(0); //分支机构id

// 获取分支机构id的函数
let getsubid = (row) => {
  searchall();
  all_organ.forEach((item) => {
    //找出点击项的分支机构的id
    if (row.subName == item.name) {
      sub_id.value = item.subId;
    }
  });
};

// 新增体检机构,添加的表单默认隐藏
let addFormVisible = ref(false);
//修改体检机构,修改的表单默认隐藏
let updateFormVisible = ref(false);

// 分页所需要的数据
const page = ref(1);
const size = ref(5);
const totalcount = ref(0);
const small = ref(true);
const disabled = ref(false);
// 表格
interface User {
  organId: number;
  organName: string;
  subName: string;
  cityName: string;
  typeName: string;
  phone: string;
  isUsed: Number | String;
}

const multipleSelection = ref<User[]>([]);
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val;
  console.log(multipleSelection.value);
};

// 待渲染的表格数据
let organization: User[] = reactive([
  {
    organId: 111,
    organName: "瑞慈",
    subName: "IFC分店",
    cityName: "广州市",
    typeName: "专门体检机构",
    phone: "020-88888888",
    isUsed: 1,
  },
]);

// 调用列表查询接口，初始化渲染展示表格数据
const show_table = () => {
  examorgan({
    cityId: 0,
    code: "",
    codeOrName: "",
    isUsed: 0,
    limit: size.value,
    organName: "",
    page: page.value,
    provinceId: 0,
    type: 0,
  }).then((res) => {
    console.log(res.data);
    totalcount.value = res.data.count;
    organization.length = 0;
    organization.push(...res.data.data);
    organization.forEach((el) => {
      el.isUsed == 1 ? (el.isUsed = "是") : (el.isUsed = "否");
    });
    // console.log(organization);
    //每页条数不够则用空值填满
    if (organization.length < size.value) {
      const diff = size.value - organization.length;
      for (let i = 0; i < diff; i++) {
        organization.push({
          organId: null,
          organName: "",
          subName: "",
          cityName: "",
          typeName: "",
          phone: "",
          isUsed: null,
        });
      }
    }
  });
  // console.log(data);
};

// 初始化表格
show_table();

// 展示在表格上面的数据，不够每页条数的用空行补充
// let tableData = computed(() => {

//   return tab_arr;
// });

let update_form = reactive({});
// 表格操作按钮(修改体检机构信息)
const update_org = (row, index: number) => {
  updateFormVisible.value = true;
  // console.log(Object.values(all_organ));
  searchall().then(() => {
    //调用所有机构查询，获取全部机构
    // console.log(row.subName);
    console.log(all_organ);
    all_organ.forEach((item) => {
      if (item.name == row.subName) {
        // console.log(item);
        Object.assign(update_form, item); //将表单传给修改页面
        update_form["organName"] = row.organName;
      }
    });
  });
  getsubid(row); //获取分支机构id
};

// 表格操作按钮(离线号源表单显示)
let offVisible = ref(false);

// 列表查询所有机构类型，赋值给下拉框
let typeall = () => {
  type_all({}).then((res) => {
    // console.log(res.data.data);
    let res_arr = res.data.data;
    res_arr.forEach((el) => {
      institu_options.push({
        id: el.organTypeId,
        type: el.organTypeName,
        isDeleted: el.isDeleted,
      });
    });
  });
};

typeall();

// 按条件搜索查询
const search = () => {
  // console.log(!isNaN(Number(form.name)));
  if (!isNaN(Number(form.name)) && form.name != "") {
    //如果输入转化为Number类型不是NaN，则加上TJJG前缀
    form.name = "TJJG" + form.name;
  } else {
    form.name = form.name;
  }

  examorgan({
    limit: size.value,
    page: page.value,
    codeOrName: form.name, //输入名字或者id
    provinceId: form.provin_sel,
    cityId: form.city_sel,
    type: form.instype,
    isUsed: form.is_using,
  }).then((res) => {
    // console.log(res.data.data);
    totalcount.value = res.data.count;
    organization.length = 0;
    organization.push(...res.data.data);
    organization.forEach((el) => {
      el.isUsed == 1 ? (el.isUsed = "是") : (el.isUsed = "否");
    });
    // console.log(organization);
    //每页条数不够则用空值填满
    if (organization.length < size.value) {
      const diff = size.value - organization.length;
      for (let i = 0; i < diff; i++) {
        organization.push({
          organId: null,
          organName: "",
          subName: "",
          cityName: "",
          typeName: "",
          phone: "",
          isUsed: null,
        });
      }
    }
  });
};

// 判断对象的所有的属性的值是否为空
let areAllPropertiesEmpty = (obj) => {
  for (let key in obj) {
    if (
      obj.hasOwnProperty(key) &&
      obj[key] !== null &&
      obj[key] !== undefined &&
      obj[key] !== ""
    ) {
      return false;
    }
  }
  return true;
};

// 分页
const handleSizeChange = (val: number) => {
  size.value = val;
  // 如果搜索的条件为空，则调用表格全部展示，否则按条件
  areAllPropertiesEmpty(form) == true ? show_table() : search();
};
const handleCurrentChange = (val: number) => {
  page.value = val;
  // 如果搜索的条件为空，则调用表格全部展示，否则按条件
  areAllPropertiesEmpty(form) == true ? show_table() : search();
};

// 重置搜索填选的值
let reset = () => {
  Object.assign(form, {
    name: "",
    provin_sel: "",
    city_sel: "",
    instype: "",
    is_using: "",
  });
  city_options.length = 0; //市的下拉框数据重置
  show_table(); //初始化表格
};

// 确认新增机构
let add_click = () => {
  // console.log(store.addform);
  let {
    cityId,
    east,
    imgUrl: imageUrl,
    isUsed,
    location,
    north,
    organName,
    phone,
    provinceId,
    status,
    name: subOrganName,
    type,
  } = store.addform;
  let sub_addform = {
    cityId,
    east,
    imageUrl,
    isUsed,
    location,
    north,
    organName,
    phone,
    provinceId,
    status,
    subOrganName,
    type,
  };
  // console.log(sub_addform);
  addorgan(sub_addform).then((res) => {
    // console.log(res);
    if (res.data.code == 0) {
      ElMessage({
        showClose: true,
        message: "添加机构信息成功了",
        type: "success",
      });
      // 重新渲染表格
      show_table();
      addFormVisible.value = false;
    }
  });
};

//修改当前选中的机构信息
let update_organ = () => {
  let {
    cityId,
    east,
    imgUrl: imageUrl,
    isUsed,
    location,
    north,
    organName,
    phone,
    provinceId,
    status,
    name: subOrganName,
    type,
  } = store.updateform;
  imageUrl ? (imageUrl = imageUrl) : (imageUrl = "");
  organName ? (organName = organName) : (organName = "");
  east ? (east = east) : (east = "");
  location ? (location = location) : (location = "");
  north ? (north = north) : (north = "");
  let sub_updateform = {
    cityId,
    east,
    imageUrl,
    isUsed,
    location,
    north,
    organName,
    phone,
    provinceId,
    status,
    subOrganName,
    type,
    subId: sub_id.value,
  };
  // console.log(sub_updateform);

  //调用修改的接口
  updateorgan(sub_updateform).then((res) => {
    console.log(res.data);
    if (res.data.code == 0) {
      ElMessage({
        showClose: true,
        message: "修改机构信息成功了",
        type: "success",
      });
      // 重新渲染表格
      show_table();
      updateFormVisible.value = false;
    }
  });
};

//批量删除的
let del_batches = (subids, deleted) => {
  delbatches({ ids: subids }).then((res) => {
    if (res.data.code == 0) {
      show_table(); //重新展示表格
      ElMessage({
        message: h("p", null, [
          h("span", null, "已删除"),
          h("i", { style: "color: teal" }, deleted),
        ]),
      });
    }
  });
};

//点击删除按钮给出提示，删除已选中
const del_checked = () => {
  //这是删除已勾选的
  if (multipleSelection.value.length == 0) {
    ElMessage({
      showClose: true,
      message: "还没有勾选哦",
      type: "warning",
    });
  } else {
    //删除已选中的
    ElMessageBox.confirm("是否删除已勾选的部分?", "注意", {
      confirmButtonText: "是的",
      cancelButtonText: "点错了",
      type: "warning",
    })
      .then(() => {
        // console.log(multipleSelection.value); //已勾选部分
        // console.log(all_organ);
        let sub_ids = [];
        all_organ.forEach((all_i) => {
          //找出勾选的分支机构
          multipleSelection.value.forEach((mul_i) => {
            if (mul_i.subName == all_i.name) {
              // console.log(all_i.subId);
              sub_ids.push(all_i.subId);
            }
          });
        });

        del_batches(sub_ids, "刚刚勾选的部分"); //调用批量删除的接口
        // del_batches
      })
      .catch(() => {
        ElMessage({
          message: h("p", null, [
            h("span", null, "您已 "),
            h("i", { style: "color: teal" }, "取消"),
            h("span", { style: "margin-left:5px" }, "删除"),
          ]),
        });
      });
  }
};

//点击删除按钮给出提示，删除未选中的
const del_unchecked = () => {
  //这是删除未勾选的
  if (multipleSelection.value.length == organization.length) {
    ElMessage({
      showClose: true,
      message: "已经全部勾选了",
      type: "warning",
    });
  } else {
    //删除已选中的
    ElMessageBox.confirm("是否删除未勾选的部分?", "注意", {
      confirmButtonText: "是的",
      cancelButtonText: "点错了",
      type: "warning",
    })
      .then(() => {
        let un_Selection = organization.filter(
          (el) => !multipleSelection.value.includes(el)
        );
        // console.log(un_Selection); //这是未被选中的部分
        let sub_ids = [];
        all_organ.forEach((all_i) => {
          //找出勾选的分支机构
          un_Selection.forEach((unsel_i) => {
            if (unsel_i.subName == all_i.name) {
              // console.log(all_i.subId);
              sub_ids.push(all_i.subId);
            }
          });
        });
        del_batches(sub_ids, "刚刚未勾选的部分"); //调用批量删除的接口
        //http请求...
      })
      .catch(() => {
        ElMessage({
          message: h("p", null, [
            h("span", null, "您已 "),
            h("i", { style: "color: teal" }, "取消"),
            h("span", { style: "margin-left:5px" }, "删除"),
          ]),
        });
      });
  }
};

// 下载excel模板文件
const downloadExcel = () => {
  const data = [
    {
      机构ID: "",
      机构名称: "",
      分支机构: "",
      所在城市: "",
      机构类型: "",
      电话: "",
      是否启用: "",
    },
  ];
  const sheet = XLSX.utils.json_to_sheet(data);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, sheet, "Sheet1");
  const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
  const blob = new Blob([excelBuffer], { type: "application/octet-stream" });
  saveAs(blob, "体检机构添新表.xlsx");
};

// 离线号源设置弹框是否显示
let formulateVisible = ref(false); // 制定号源

//离线号源里面的数据
let cander_data = reactive([]);
let last_day = ref("");
let first_day = ref("");
// cander_data[cander_data.length - 1].date
// cander_data[0].date

// 通过分支机构id、当前日期获取离线号源
let stocklist = (sub_id) => {
  // console.log(nowdate);
  // console.log(organId);
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth() + 1; // 注意月份从 0 开始计数，所以需要加 1
  const day = today.getDate();
  let now_date = ``;
  // 如果月份或者日期小于10，则在前面再加个0
  if (month < 10 && day >= 10) {
    now_date = `${year}-0${month}-${day}`;
  } else if (month < 10 && day < 10) {
    now_date = `${year}-0${month}-0${day}`;
  } else if (month >= 10 && day < 10) {
    now_date = `${year}-${month}-0${day}`;
  } else {
    now_date = `${year}-${month}-${day}`;
  }
  // 查询号源
  stock_list({ date: now_date, subId: sub_id }).then((res) => {
    console.log(res);
    // console.log(JSON.parse(res.data.data));
    cander_data.length = 0;
    cander_data.push(...JSON.parse(res.data.data));
    last_day.value = cander_data[cander_data.length - 1].date; //号源的最后一天
    first_day.value = cander_data[0].date; //号源的第一天
    // console.log(cander_data);
  });
};

// 点击离线号源设置
const off_line = (row, index: number) => {
  // console.log(row.organId);
  // 获取分支机构的id
  getsubid(row);
  stocklist(sub_id.value); // 调用查询号源的函数
  // console.log(sub_id.value);
  // console.log(row);
  of_organ.value = row.organName; //显示所属主机构
  of_suborgan.value = row.subName; //显示所属分支机构
  offVisible.value = true;
};

// 点击配置号源规则
let sourcerule = () => {
  offVisible.value = false;
  formulateVisible.value = true;
};

//取消号源规则
let rulecancel = () => {
  formulateVisible.value = false; //弹框二隐藏
  offVisible.value = true; //弹框一显示
};

//设置只能选择今天以及以后的日期
let disabledDate = (time) => {
  const firstday = new Date(
    new Date(first_day.value).getFullYear(),
    new Date(first_day.value).getMonth(),
    new Date(first_day.value).getDate()
  ); // 获取号源第一个日期
  const lastday = new Date(
    new Date(last_day.value).getFullYear(),
    new Date(last_day.value).getMonth(),
    new Date(last_day.value).getDate()
  ); // 获取号源最后一个日期
  const selectedDate = new Date(
    time.getFullYear(),
    time.getMonth(),
    time.getDate()
  ); // 选中日期
  return selectedDate < firstday || selectedDate > lastday; // 禁用今天以前的日期
};

// 将选择的日期转化为'年-月-日格式的函数
let trans_date = (date) => {
  return date
    .toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    })
    .replace(/\//g, "-");
};
//确定配置修改号源规则
let ruleconfirm = () => {
  formulateVisible.value = false; //弹框二隐藏
  offVisible.value = true; //弹框一显示
  // console.log(mulate_form.time[0]);
  const date_1 = new Date(mulate_form.time[0]);
  const date_2 = new Date(mulate_form.time[1]);
  // console.log(trans_date(date_1));
  // console.log(trans_date(date_2));
  // console.log(sub_id.value);
  // console.log(mulate_form.repetition);
  // console.log(mulate_form.subscribe);

  let rule_sub = {
    startDate: trans_date(date_1),
    endDate: trans_date(date_2),
    subId: sub_id.value,
    totalNum: mulate_form.subscribe,
    week: mulate_form.repetition,
  };
  // console.log(rule_sub);
  update_Batches(rule_sub).then((res) => {
    console.log(res.data);
    if (res.data.code == 0) {
      //重新查询渲染号源
      stocklist(sub_id.value);
      ElMessage({
        showClose: true,
        message: "配置号源规则成功",
        type: "success",
      });
    } else if (res.data.code == 20001) {
      ElMessage({
        showClose: true,
        message: "配置号源规则失败",
        type: "error",
      });
    }
  });
  // console.log(formattedDate);
};

let update_show = ref(""); //修改号源按钮是否显示
let upmulateVisible = ref(false); //修改号源弹窗是否显示
let is_updateshow = (data) => {
  //点击某一项，把此项的日期赋值给update_show，以显示修改号源按钮
  // console.log(data.day); //显示日期
  let dateval = data.day;
  update_show.value = dateval;
  // console.log(update_show == dateval);
};

let update_source = reactive({
  date: "",
  totalNum: null,
  id: null,
  subOrganId: null,
});

let date_show = ref("");
// 点击修改号源的按钮
let update_mulate = (day) => {
  // console.log(day); //日期参数
  // console.log(cander_data.find((item) => item.date === day).totalNum); //原来的号源数
  // console.log(sub_id.value); //分支机构id
  // console.log(uodate_source.totalNum); //待修改的号源数
  // console.log(cander_data);
  // console.log(cander_data);

  update_source.date = day;
  // 转化为年月日标准格式，将日期格式化为目标字符串
  const to_year = new Date(day).getFullYear();
  const to_month = new Date(day).getMonth() + 1;
  const to_day = new Date(day).getDate();
  date_show.value = to_year + "年" + to_month + "月" + to_day + "日";
  update_source.totalNum = cander_data.find((item) => item.date === day)
    ? Number(cander_data.find((item) => item.date === day).totalNum)
    : null;
  update_source.id = cander_data.find((item) => item.date === day)
    ? cander_data.find((item) => item.date === day).id
    : null;
  update_source.subOrganId = sub_id.value;

  upmulateVisible.value = true;
};
//确认修改号源
let upmulate_con = () => {
  let { date, totalNum, id, subOrganId } = update_source;
  totalNum = Number(totalNum);
  // console.log({ date, totalNum, id, subOrganId });
  update_stock({ date, totalNum, id, subOrganId }).then((res) => {
    // console.log(res.data);
    if (res.data.code == 0) {
      //重新查询渲染号源
      stocklist(subOrganId);
      ElMessage({
        showClose: true,
        message: "修改号源成功",
        type: "success",
      });
    }
  });
  upmulateVisible.value = false;
};

// 制定号源规则的表单(生效时间、重复、可预约号源数)
let mulate_form = reactive({ time: "", repetition: [], subscribe: "" });
let weekdays = reactive([
  { val: "周日" },
  { val: "周一" },
  { val: "周二" },
  { val: "周三" },
  { val: "周四" },
  { val: "周五" },
  { val: "周六" },
]);

let search_province = () => {
  // 获取省机构的函数
  province_all({}).then((res) => {
    // console.log(res.data.data);
    province_options.length = 0;
    province_options.push(...res.data.data);
    // console.log(province_options);
  });
};

// 获取所有省机构名称
search_province();

// 获取当前选择的省下的市
let search_cities = (id) => {
  // console.log(id);
  city_search({ id }).then((res) => {
    // console.log(res.data);
    city_options.length = 0; //市的下拉框数据重置
    city_options.push(...res.data.data);
    form.city_sel = ""; //每次选择不一样的省的时候，市的值置空
  });
};
</script>

<style scoped lang="less">
.phyorgan {
  width: 100%;
  height: 90vh;
  box-sizing: border-box;
  overflow-x: hidden;
}

// 主要内容区域
.phy_main {
  width: 100%;
  margin-top: 1vh; //还有1vh的留白
  background: rgb(255, 255, 255);
}

// 标题“数据筛选”
.title_2 {
  width: 100%;
  height: 3rem;
  line-height: 3rem;
  padding-left: 2rem;
  box-sizing: border-box;
  border: 1px solid rgba(153, 153, 153, 0.221);
  border-bottom: 0;
  font-weight: bold;
  font-size: 1.2rem;
}

// 输入框组成的搜索表单
.el-form.search_line {
  width: 100%;
  min-height: 5rem;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  border: 1px solid rgba(153, 153, 153, 0.221);
  padding-right: 2%;
  box-sizing: border-box;
}

.el-form.search_line .el-form-item {
  margin-bottom: 0; // 清除输入框自带的外下边距
}

// 所在省市两个下拉框
.el-form.search_line .el-form-item:nth-child(2) .el-select {
  margin-right: 0.2rem;
}

// 添加、删除、导入
.three-buttons {
  margin-top: 1.2rem;
  padding-left: 2rem;
  box-sizing: border-box;
}

// 表格
.el-table {
  margin-top: 1.2rem;
}

// 分页器
.demo-pagination-block {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  // position: absolute;
  // right: 1%;
  // bottom: 2.5rem;
  margin-top: 1.2rem;
}

// .custom-pagination
//   .el-pagination.is-background
//   .el-pager
//   > li.is-active.number {
//   background-color: antiquewhite;
// }

//新增体检机构标题
// header.el-dialog__header {
//   background-color: rgba(222, 222, 222, 0.471);
// }
// 配置号源规则、所属机构
.formulate-line {
  width: 100%;
  display: flex;
  justify-content: space-between;
  > div > .el-tag {
    margin-left: 8px;
  }
}

.formulate-outer {
  user-select: none;
  position: relative;
  width: 100%;
  height: 100%;
  // 主要内容
  > .off-linenumso {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    font-size: 10px;
    // 总号源(可修改)
    .totnumso-1 {
      width: 100%;
      display: flex;
      align-items: center;
      > .sign {
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background-color: rgb(0, 227, 12);
      }
      > span {
        margin: 0 5px;
      }
      > .number {
        color: rgb(0, 227, 12);
      }
    }
    // 总号源(不可修改)
    .totnumso-2 {
      width: 100%;
      display: flex;
      align-items: center;
      > .sign {
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background-color: rgb(197, 197, 197);
      }
      > span {
        margin: 0 5px;
      }
      > .number {
        color: rgb(197, 197, 197);
      }
    }
    // 余数(可修改)
    .remainder-1 {
      width: 100%;
      display: flex;
      align-items: center;
      > .sign {
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background-color: rgb(227, 0, 0);
      }

      > span {
        margin: 0 5px;
      }

      > .number {
        color: rgb(227, 0, 0);
      }
    }
    // 余数(不可修改)
    .remainder-2 {
      width: 100%;
      display: flex;
      align-items: center;
      > .sign {
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background-color: rgb(197, 197, 197);
      }

      > span {
        margin: 0 5px;
      }

      > .number {
        color: rgb(197, 197, 197);
      }
    }
  }
  // 修改号源(隐藏背景层)
  .update-formulate {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 100;
    display: flex;
    justify-content: flex-end;
    // align-items: flex-end;
    // background-color: rgba(104, 104, 104, 0.202);
    > .el-button {
      margin-top: 15%;
    }
  }
}

// 制定号源规则表单
.el-form.mulate-rule {
  .el-form-item {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    span {
      width: 6.6rem;
      text-align: right;
      margin-right: 20px;
      i {
        color: rgb(250, 83, 83);
        display: inline-block;
        transform: translateX(-10px);
      }
    }
    .el-input {
      width: 92px;
      margin-right: 8px;
    }
  }
}

//修改号源
.el-dialog .update-source {
  width: 100%;
  display: flex;
  // justify-content: center;
  > div {
    display: flex;
    width: 80%;
    > span {
      width: 50%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      color: rgb(147, 147, 147);
    }
    > .el-input {
      margin-left: 20px;
    }
  }
}
</style>
